package com.hxb.example.oauth.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.lang.Snowflake;
import com.hxb.example.RedisUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AuthorizationController {

    @GetMapping("/getCaptcha")
    public Map<String,Object> getCaptcha(HttpServletResponse response) {
        // 使用hutool-captcha生成图形验证码
        // 定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(150, 40, 4, 2);
        // 这里应该返回一个统一响应类，暂时使用map代替
        Map<String,Object> result = new HashMap<>();
        result.put("code", HttpStatus.OK.value());
        result.put("success", true);
        result.put("message", "获取验证码成功.");
        result.put("data", captcha.getImageBase64Data());
        // 存入session中
        String nextId = new Snowflake().nextIdStr();
        response.addCookie(new Cookie("jtc", nextId));
        // response.addCookie(ResponseCookie.from("captcha", nextId).path("/").httpOnly(true).maxAge(60).build());
        RedisUtil.set(nextId, captcha.getCode(), 60);
        return result;
    }

}
